<template>
  <el-container class="home-container">
    <el-aside class="sidebar" style="width: 240px;">
      <div class="logo-container">
        <img src="/warehouse.png" width="32" height="32" />
        <span class="logo-text">供应链系统</span>
      </div>
      <el-menu
        class="el-menu-vertical"
        :default-active="$route.path"
        background-color="#001529"
        text-color="#fff"
        active-text-color="#409EFF"
        :router="true"
        :collapse-transition="false"
      >
        <el-sub-menu v-for="firstMenu,idx of menuList" :key="firstMenu.authId" :index="String(idx)">
          <template #title>
            <el-icon v-if="firstMenu.authName=='用户管理'" class="menu-icon"><User /></el-icon>
            <el-icon v-if="firstMenu.authName=='角色管理'" class="menu-icon"><UserFilled /></el-icon>
            <el-icon v-if="firstMenu.authName=='权限管理'" class="menu-icon"><Lock /></el-icon>
            <el-icon v-if="firstMenu.authName=='商品管理'" class="menu-icon"><Goods /></el-icon>
            <el-icon v-if="firstMenu.authName=='采购管理'" class="menu-icon"><ShoppingCart /></el-icon>
            <el-icon v-if="firstMenu.authName=='入库管理'" class="menu-icon"><Finished /></el-icon>
            <el-icon v-if="firstMenu.authName=='出库管理'" class="menu-icon"><SwitchButton /></el-icon>
            <el-icon v-if="firstMenu.authName=='统计查询'" class="menu-icon"><DataLine /></el-icon>
            <el-icon v-if="firstMenu.authName=='站内通知'" class="menu-icon"><Bell /></el-icon>
            <el-icon v-if="firstMenu.authName=='调货管理'" class="menu-icon"><Van /></el-icon>
            <el-icon v-if="firstMenu.authName=='仓库管理'" class="menu-icon"><House /></el-icon>
            <el-icon v-if="firstMenu.authName=='供货商管理'" class="menu-icon"><Shop /></el-icon>
            <el-icon v-if="firstMenu.authName=='产地管理'" class="menu-icon"><Location /></el-icon>
            <span>{{firstMenu.authName}}</span>
          </template>
          <el-menu-item 
            v-for="secondMenu of firstMenu.childAuth" 
            :key="secondMenu.authId" 
            :index="getMenuPath(secondMenu)"
            @click="handleMenuClick(secondMenu)"
            class="submenu-item"
          >
            <template v-if="isSupplyMenu(secondMenu)">
              <el-icon><Shop /></el-icon>
            </template>
            <span>{{secondMenu.authName}}</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    <el-container class="main-container">
      <el-header class="main-header">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <template v-if="$route.meta && $route.meta.nav">
              <el-breadcrumb-item v-for="path in $route.meta.nav" :key="path">
                {{path}}
              </el-breadcrumb-item>
            </template>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click">
            <span class="user-profile">
              <el-avatar :size="32" icon="UserFilled" />
              <span class="user-name">{{currUser.userName}}</span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="openUserInfo">
                  <el-icon><User /></el-icon>
                  个人信息
                </el-dropdown-item>
                <el-dropdown-item divided @click="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-main class="main-content">
        <router-view v-slot="{ Component }">
          <keep-alive :include="['userList', 'roleList', 'authList']">
            <component 
              :is="Component" 
              :key="$route.fullPath"
              v-if="Component"
            />
          </keep-alive>
        </router-view>
      </el-main>
      <el-footer class="main-footer">
        <p>版权所有 &copy; 2025 企业大宗商品供应链优化系统</p>
      </el-footer>
    </el-container>
    <!-- 添加个人信息弹窗组件 -->
    <user-info ref="userInfoRef"></user-info>
  </el-container>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { tip, get, del, removeLocalToken } from "@/common";
import {
  Location,
  User,
  UserFilled,
  Lock,
  Goods,
  ShoppingCart,
  Finished,
  SwitchButton,
  DataLine,
  Bell,
  Van,
  House,
  ArrowDown,
  Shop
} from '@element-plus/icons-vue'
import UserInfo from './user/user-info.vue';

const router = useRouter(); // 获取路由器
const userInfoRef = ref();

// 当前路径
/* const paths = ref([]);
const selectMenu = (first, second) => {
  paths.value = [first, second];
} */

// 获取当前登录用户
const currUser = ref({});
const getCurrentUser = async () => {
  try {
    const result = await get("/curr-user");
    currUser.value = result.data;
  } catch (error) {
    console.error('Failed to fetch current user:', error);
    tip.error('获取当前用户信息失败');
  }
}

// 退出
const logout = () => {
  del("/logout").then(result =>{
    // 删除本地token
    removeLocalToken();
    // 替换路由
    router.replace("/login");
    tip.success("您已退出系统！");
  });
}

// 获取所有权限
const menuList = ref([]);
const getMenuList = async () => {
  try {
    const result = await get("/user/auth-list");
    menuList.value = result.data;
  } catch (error) {
    console.error('Failed to fetch menu list:', error);
    tip.error('获取菜单列表失败');
  }
}

// 初始化数据
const initData = async () => {
  await Promise.all([getCurrentUser(), getMenuList()]);
}
initData();

// 打开个人信息弹窗
const openUserInfo = () => {
  userInfoRef.value.open(currUser.value.userId);
};

// 判断是否是供货商菜单
const isSupplyMenu = (menu) => {
  return menu.authName === '供货商列表';
};

// 获取菜单路径
const getMenuPath = (menu) => {
  if (isSupplyMenu(menu)) {
    return '/supply/list';
  }
  return menu.authUrl || '';
};

// 处理菜单点击
const handleMenuClick = (menu) => {
  console.log('Menu clicked:', menu);
  const path = getMenuPath(menu);
  
  if (path) {
    router.push(path).catch(err => {
      if (err.name !== 'NavigationDuplicated') {
        console.error('Navigation failed:', err);
      }
    });
  }
};

</script>

<style scoped>
.home-container {
  height: 100vh;
  background-color: #f0f2f5;
}

.sidebar {
  background-color: #001529;
  box-shadow: 2px 0 6px rgba(0,21,41,.35);
  z-index: 10;
  transition: all 0.3s ease;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  background-color: #002140;
}

.logo-text {
  color: white;
  font-size: 18px;
  font-weight: 600;
  margin-left: 12px;
  white-space: nowrap;
}

.el-menu-vertical {
  border-right: none;
}

.menu-icon {
  margin-right: 10px;
  font-size: 18px;
}

.submenu-item {
  padding-left: 50px !important;
}

.main-container {
  min-height: 100vh;
  background-color: #f0f2f5;
}

.main-header {
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 60px;
  position: relative;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-profile {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.user-profile:hover {
  background: rgba(0,0,0,.025);
}

.user-name {
  margin: 0 8px;
  color: rgba(0,0,0,.85);
}

.main-content {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 120px);
}

.main-footer {
  text-align: center;
  padding: 16px 24px;
  color: rgba(0,0,0,.45);
  font-size: 14px;
  background-color: #f0f2f5;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.15s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

:deep(.el-menu-item.is-active) {
  background-color: #1890ff !important;
}

:deep(.el-sub-menu__title:hover) {
  background-color: #002140 !important;
}

:deep(.el-menu-item:hover) {
  background-color: #002140 !important;
}

:deep(.el-breadcrumb__inner.is-link) {
  color: #1890ff;
  font-weight: 400;
}

:deep(.el-breadcrumb__inner) {
  color: rgba(0,0,0,.45);
  font-weight: 400;
}
</style>